class websocketUtil {
	constructor(url, time, clientId) {
		/*
		url 是请求的后端的地址
		time 是心跳包的时间
		*/
		this.is_open_socket = false //避免重复连接
		this.url = url //地址
		this.data = null
		//心跳检测
		this.timeout = time //多少秒执行检测
		this.heartbeatInterval = null //检测服务器端是否还活着
		this.reconnectTimeOut = null //重连之后多久再次重连
		this.clientId = clientId
		this.token = uni.getStorageSync('token')

		try {
			return this.connectSocketInit()
		} catch (e) {
			console.log('catch');
			this.is_open_socket = false
			this.reconnect();
		}
	}

	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit() {
		//console.log(this.token)
		this.socketTask = uni.connectSocket({
			url: this.url,
			header: {
				'Authorization': 'Bearer=' + this.token // 在请求头中携带token
				//'content-type': 'application/json',
				//token: this.token, //您可根据如本地存储或者vuex再此处使用逻辑或 来插入token
			},
			success: () => {
				console.log("正准备建立websocket中...");
				//心跳检测
				//this.start()

				// 返回实例
				return this.socketTask
			},

		});
		this.socketTask.onOpen((res) => {
			console.log("WebSocket连接正常！");
			clearTimeout(this.reconnectTimeOut)
			clearTimeout(this.heartbeatInterval)
			this.is_open_socket = true;

			var loginData = {
				type: 1,
				msg: {
					userId: uni.getStorageSync('userId'),
					username: "123",
					password: "123",
					clientId: this.clientId
				}
			}
			//console.log(JSON.stringify(loginData))
			//登录
			this.socketTask.send({
				data: JSON.stringify(loginData),
				async success() {
					//that.changeLiveStatus(1);
					//console.log("消息发送成功");
				},
			});


			this.start();
		})

		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onClose((res) => {
			if (res.code === 1000) {
				this.is_open_socket = true;
			} else {
				this.is_open_socket = false;
			}
			console.log("已经被关闭了", res)
			this.reconnect();
		})
	}

	//发送消息
	send(value) {
		var result = false
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		this.socketTask.send({
			data: JSON.stringify(value.data),
			async success() {
				result = true
			},
		});
		return result
	}
	//开启心跳检测
	start() {
		this.heartbeatInterval = setInterval(() => {
			this.data = {
				type: "start"
			}

			// var loginData = {
			// 	type: 2,
			// 	msg: {
			// 		userId: uni.getStorageSync('userId'),
			// 		time: Date.parse(new Date()) + ''
			// 	}
			// }

			// this.socketTask.send({
			// 	data: JSON.stringify(loginData),
			// 	async success() {
			// 		//that.changeLiveStatus(1);
			// 		//console.log("消息发送成功");
			// 	},
			// });

			//this.send(JSON.stringify(this.data));
			//console.log('心跳包');
		}, this.timeout)
	}
	//重新连接
	reconnect() {
		//停止发送心跳
		clearInterval(this.heartbeatInterval)
		//如果不是人为关闭的话，进行重连
		if (!this.is_open_socket) {
			this.reconnectTimeOut = setTimeout(() => {
				//this.connectSocketInit();

				uni.myWebsocket.socketTask.close
				uni.myWebsocket = ''
				uni.$connectSocketInit.connectSocket(uni.$basePort)

			}, 1000)
		}
	}
	//接收消息
	receiveMsg() {
		var that = this
		return new Promise(resolve => {
			that.socketTask.onMessage((res) => {
				var msg = JSON.parse(res.data)
				resolve(msg)
			});
		})

	}

	// 主动关闭socket连接
	close() {
		// if (!this.is_open_socket) {
		// 	return
		// }
		this.socketTask.close({
			success(res) {
				// uni.showToast({
				// 	title: 'SocketTask 关闭成功',
				// 	icon: "none"
				// });
				console.log("已经被关闭了", res)
			}
		});
	}
}

module.exports = websocketUtil